package org.sean.framework.web.converter;

import org.sean.framework.bean.BaseResult;
import org.sean.framework.code.StatusInfo;
import org.sean.framework.util.ObjectUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 响应结构体使用 BaseResult
 *
 * @author xielei
 */
public class DefaultResponseBodyConverter implements BaseResponseBodyConverter<Object> {

    @Override
    public BaseResult convert(Object body) {
        if (body instanceof BaseResult) {
            return (BaseResult) body;
        }
        BaseResult<Object> result = new BaseResult<>();
        // 处理集合类型
        if (body instanceof Collection) {
            List<Object> list = new ArrayList<>();
            list.addAll((Collection<?>) body);
            result.setList(list);
        } else if (ObjectUtil.isArray(body)) { //数组类型
            Object[] array = ObjectUtil.getArray(body);
            if (array != null) {
                result.setList(Arrays.asList(array));
            }
        } else {
            result.setData(body);
        }
        result.setState(BaseResult.CODE_SUCCESS);
        return result;
    }

    @Override
    public BaseResult handleStatus(StatusInfo statusInfo) {
        BaseResult<Object> result = new BaseResult<>();
        result.setState(statusInfo.getCode());
        result.setLevel(statusInfo.getLevel());
        result.setMessage(statusInfo.getMessage());
        return result;
    }
}
